package org.lisen.cors.config;

import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import java.util.List;

/**
 * 跨域配置
 *
 * @author laughing
 * @date 2020/9/26
 * @site https://www.lisen.org
 */
@Configuration
@ConfigurationProperties(prefix = "cors")
@Getter
@Setter
public class CorsFilterConfig {

    private boolean allowCredentials;
    private List<String> allowedOrigin;
    private List<String> allowMethods;
    private long maxAge;
    private String path;

    /**
     * 配置跨域
     *
     * @return CorsFilter
     */
    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        this.allowedOrigin.forEach(corsConfiguration::addAllowedOrigin);
        this.allowMethods.forEach(corsConfiguration::addAllowedMethod);
        corsConfiguration.setAllowCredentials(this.allowCredentials);
        corsConfiguration.setMaxAge(this.maxAge);
        UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
        urlBasedCorsConfigurationSource.registerCorsConfiguration(this.path, corsConfiguration);
        return new CorsFilter(urlBasedCorsConfigurationSource);
    }

}
